<?php
namespace app\admin\controller;

use think\Controller;

use app\admin\service\Capital as CapitalService;
use think\Request;

class Capital extends Base
{
    public $sCapital;

    public function __construct()
    {
        parent::__construct();
        $this->sCapital = new CapitalService();
    }

    /**
     * @auther zlq
     * @create_time 2020/5/21 22:32
     * @description 资金记录列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function capitalList()
    {
        $param['page_size'] = input('page_size', 10);
        $param['capital_type'] = input('capital_type', 0);
        $param['capital_status'] = input('capital_status', 0);
        $param['user'] = input('user', 0);
        $param['start_date'] = input('start_date', '');
        $param['end_date'] = input('end_date', '');
        $list = $this->sCapital->getCapitalList($param);
        $capital_type = config('dic.capital_type');
        $capital_status = config('dic.capital_status');
        $user_list = $this->sCapital->getCapitalUserList();
        $this->assign('capital_type', $capital_type);
        $this->assign('capital_status', $capital_status);
        $this->assign('user_list', $user_list);
        $this->assign('param', $param);
        $this->assign('list', $list);
        return $this->fetch('capital_list');
    }

    /**
     * @auther zlq
     * @create_time 2020/5/23 10:27
     * @description 处理资金单审核
     */
    public function auditCapital()
    {
        $id = input('id', 0);
        $type = input('type', 2);
        $file = input('file', "");
        $remark = input('remark', "");
        $type = (int)$type;
        if ($type == 1) {
            $res = $this->sCapital->auditCapitalPass($id, $remark, $file);
            switch ($res) {
                case 1:
                    return $this->apiSuccess("审核通过提现单成功");
                    break;
                case 2:
                    $msg  = "支付宝转账失败,请重试";
                    $error_msg = session('error_msg');
                    if ($error_msg) {
                        $msg .= ': '. $error_msg;
                    }
                    return $this->apiSuccess($msg);
                    break;
                case -1:
                    return $this->apiError("参数不正确,请重试");
                    break;
                case -2:
                    return $this->apiError("提现单信息不正确,请重试");
                    break;
                case -3:
                    return $this->apiError("提现单状态不正确,请重试");
                    break;
                case -4:
                    return $this->apiError("提现单用户提现账号不正确,请重试");
                    break;
                default:
                    return $this->apiError("审核通过提现单失败,请重试");
                    break;
            }
        } else {
            $res = $this->sCapital->auditCapitalRefuse($id, $remark, $file);
            switch ($res) {
                case 1:
                    return $this->apiSuccess("审核退回提现单成功");
                    break;
                case -1:
                    return $this->apiError("参数不正确,请重试");
                    break;
                case -2:
                    return $this->apiError("提现单信息不正确,请重试");
                    break;
                case -3:
                    return $this->apiError("提现单状态不正确,请重试");
                    break;
                case -4:
                    return $this->apiError("提现用户信息不正确,请重试");
                    break;
                default:
                    return $this->apiError("审核退回提现单失败,请重试");
                    break;
            }
        }
    }

    /**
     * @auther zlq
     * @create_time 2020/5/21 22:32
     * @description 导出数据到Excel
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function exportCapital()
    {
        $ids = input('ids', '');
        $ids = trim($ids, '-');
        if ($ids) {
            $param['ids'] = $ids;
            $data = $this->sCapital->getCapitalListExcel(['ids' => $ids], 1);
        } else {
            $param['capital_type'] = input('capital_type', 0);
            $param['capital_status'] = input('capital_status', 0);
            $param['user'] = input('user', 0);
            $data = $this->sCapital->getCapitalListExcel($param, 2);
        }
        if (empty($data)) {
            $this->error('数据为空,无法导出');
        }
        $capital_type = config('dic.capital_type');
        $capital_status = config('dic.capital_status');
        // 导出表格
        require_once  EXTEND_PATH . 'PHPExcel/Classes/PHPExcel.php';
        require_once  EXTEND_PATH . 'PHPExcel/Classes/PHPExcel/Worksheet/Drawing.php';
        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        $objReader->setIncludeCharts(TRUE);
        //加载模板
        $objPHPExcel = $objReader->load( EXTEND_PATH . "PHPExcel/Examples/templates/capital.xlsx");
        $row = $baseRow = 1;
        $column = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
        $style_array = [
            'borders' => [
                'allborders' => [
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                ]
            ]
        ];
        if($data){
            foreach($data as $r => $dataRow) {
                $row++ ;
                $objPHPExcel->getActiveSheet()
                    ->setCellValue('A' . $row, ($r+1))
                    ->setCellValue('B' . $row, $dataRow['id'])
                    ->setCellValue('C' . $row, $capital_type[$dataRow['type']])
                    ->setCellValue('D' . $row, $dataRow['amount'])
                    ->setCellValue('E' . $row, $dataRow['capital'])
                    ->setCellValue('F' . $row, $dataRow['account_user'])
                    ->setCellValue('G' . $row, $dataRow['account_code'])
                    ->setCellValue('H' . $row, $capital_status[$dataRow['status']])
                    ->setCellValue('I' . $row, get_user_name($dataRow['dd_user_id']))
                    ->setCellValue('J' . $row, $dataRow['create_time']);
                $objPHPExcel->getActiveSheet()->getRowDimension($row)->setRowHeight(20);
                foreach ($column as $item) {
                    $objPHPExcel->getActiveSheet()->getStyle($item . $row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                    $objPHPExcel->getActiveSheet()->getStyle($item . $row)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                    $objPHPExcel->getActiveSheet()->getStyle($item . $row)->applyFromArray($style_array);
                }
            }
        }
        ob_end_clean();//清除缓冲区,避免乱码
        // Redirect output to a client's web browser (Excel5)
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.date("Y-m-d H:i:s").'记录.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        // If you're serving to IE over SSL, then the following may be needed
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->setIncludeCharts(TRUE);
        $objWriter->save('php://output');
    }

    // 接受上传文件接口
    public function uploadFile(Request $request)
    {
        $file = $request->file('file');
        if (empty($file)) {
            return json(['code' => -1, "msg" => "上传文件为空", 'data' => ['src' => '']]);
        }
        $error = $file->getError();
        if (!empty($error)) {
            return json(['code' => -1, "msg" => $error, 'data' => ['src' => '']]);
        }
        $file_data = $file->getInfo();
        if(is_uploaded_file($file_data['tmp_name'])){
            $file_name = $file_data['name'];
            $ext_name = strrchr($file_name, '.');
            $new_name = mt_rand(1000, 9999) . mt_rand(100, 999) . $ext_name;
            $dir_path = date("Y/m/d");
            $upload_dir_path =  'static/upload/' . $dir_path . '/';
            if (!is_dir($upload_dir_path)) {
                mkdir($upload_dir_path, 0777,true);
            }
            $upload_path  = $upload_dir_path . $new_name;
            $tmp_name = $file_data["tmp_name"];//上传文件的临时存放路径
            move_uploaded_file($tmp_name, $upload_path);
            $network_path = '/static/upload/' . $dir_path . '/' . $new_name;
            return json(['code' => 0, "msg" => "文件上传成功", 'data' => ['src' => $network_path]]);
        }
        else{
            return json(['code' => 1, "msg" => "文件上传失败,请重试", 'data' => ['src' => '']]);
        }
    }
}